package com.chenjiaru.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chenjiaru.util.constant.Constant;
import com.chenjiaru.util.entity.IndexInfo;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class CommonUtil {

    /**IndexInfo Map集合**/
    private volatile static Map<String, IndexInfo> indexInfoMap = new ConcurrentHashMap<>();

    /**
     * 获取指定类的所有 Field 的map
     * @param clazz
     * @return
     */
    public static Map<String, Field> getFieldMap(Class clazz) {
        Map<String, Field> map = new HashMap();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            map.put(field.getName(), field);
        }
        return map;
    }

    /**
     * 获取指定对象，指定的字段的值
     * @param obj
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object obj, String fieldName) {
        Field field = getFieldMap(obj.getClass()).get(fieldName);
        Object value = null;
        try {
            field.setAccessible(true);
            value = field.get(obj);
        }catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 获取索引库基础信息对象
     * @param clazz     实体类
     * @return
     */
    public static IndexInfo getIndexInfo(Class<?> clazz) {
        String alias = getAlias(clazz);
        IndexInfo indexInfo = indexInfoMap.get(alias);
        if (indexInfo == null) {
            indexInfo = new IndexInfo();
            indexInfo.setIndexName(YamlUtil.getValueToString(Constant.FILE_PATH, Constant.ELASTIC_SEARCH, Constant.INDICES, alias, Constant.INDEX_NAME));
            indexInfo.setPrimaryKey(YamlUtil.getValueToString(Constant.FILE_PATH, Constant.ELASTIC_SEARCH, Constant.INDICES, alias, Constant.PRIMARY_KEY));
            indexInfoMap.put(alias, indexInfo);
        }
        return indexInfo;
    }


    /**
     * 根据类获取别名（首字母小写）
     * @param clazz     实体类
     * @return
     */
    public static String getAlias(Class<?> clazz) {
        String alias = clazz.getSimpleName();
        alias = alias.substring(0,1).toLowerCase() + alias.substring(1);
        return alias;
    }

    /**
     * 把source的json字符串转成{@link T}实体
     * @param primaryKeyColumn  主键列
     * @param primaryKeyValue  主键的值
     * @param source    source的json字符串
     * @param clazz     实体类
     * @param <T>
     * @return
     */
    public static <T> T sourceToEntity(String primaryKeyColumn, String primaryKeyValue, String source, Class<T> clazz) {
        JSONObject json = JSON.parseObject(source);
        json.put(primaryKeyColumn, primaryKeyValue);
        T t = JSON.toJavaObject(json, clazz);
        return t;
    }

}
